package com.atguigu.flink.chapter05.mode;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2022/7/3 10:16
 */
public class Flink02_WC_UnBounded_Lambda {
    public static void main(String[] args) throws Exception {
        System.out.println("main.....");
        // 1. 创建流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
        // 2. 通过环境从source获取一个流(source)  file
//        DataStreamSource<String> source = env.readTextFile("input/words.txt");
        DataStreamSource<String> source = env.socketTextStream("hadoop162",9999);
        // 3. 对流做各种转换(transform)
        SingleOutputStreamOperator<String> wordStream = source
            .flatMap((String line, Collector<String> out) -> {
                for (String word : line.split(" ")) {
                    out.collect(word);
                }
            })
            .returns(Types.STRING);
        
        SingleOutputStreamOperator<Tuple2<String, Long>> wordOneStream = wordStream
            .map(word -> Tuple2.of(word, 1L))
            .returns(Types.TUPLE(Types.STRING, Types.LONG));
        
        KeyedStream<Tuple2<String, Long>, String> keyedStream = wordOneStream
            .keyBy(t -> t.f0);
        
        SingleOutputStreamOperator<Tuple2<String, Long>> resultStream = keyedStream.sum(1);
        // 4.输出(sink)
        resultStream.print();
        
        // 5. 执行流环境
        env.execute();
    }
}
/*
1. 创建SparkContext

2. 通过上下文从source获取一个rdd

3. 对rdd做各种转换

4. 执行一个行动算子

5. 启动上下文

 */